package org.smart4j.framework.helper;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smart4j.framework.annotation.Action;
import org.smart4j.framework.bean.Handler;
import org.smart4j.framework.bean.Request;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by Wenxin on 2017/2/25.
 */
public class ControllerHelper {
    private static final Logger LOGGER = LoggerFactory.getLogger(ControllerHelper.class);
    private static final Map<Request, Handler> ACTION_MAP = new HashMap<>();

    static {
//        获取所有的Controller类
        Set<Class<?>> controllerClassSet = ClassHelper.getControllerClassSet();

//        遍历Controller类
        if (CollectionUtils.isNotEmpty(controllerClassSet)) {
            for (Class<?> cls : controllerClassSet) {
//                获取类中定义的所有方法
                Method[] declaredMethods = cls.getDeclaredMethods();
                if (ArrayUtils.isNotEmpty(declaredMethods)) {
//                  遍历方法
                    for (Method method : declaredMethods) {
                        if (method.isAnnotationPresent(Action.class)) {
                            Action action = method.getAnnotation(Action.class);
                            String mapper = action.value();
                            if (mapper.matches("\\w+:(/\\w*)+")) {
                                String[] array = mapper.split(":");
                                if (ArrayUtils.isNotEmpty(array) && array.length == 2) {
                                    String requestMethod = array[0].trim().toLowerCase();
                                    String requestPath = array[1].trim();
                                    Request request = new Request(requestMethod, requestPath);
                                    Handler handler = new Handler(method, cls);
                                    ACTION_MAP.put(request, handler);
                                    LOGGER.debug("scan for action: {}",action.value());
                                }
                            }
                        }
                    }
                }

            }
        }

    }

    public static Handler getHandler(String requestMethod, String requestPath) {
        Request request = new Request(requestMethod, requestPath);
        if (ACTION_MAP.containsKey(request)) {
            return ACTION_MAP.get(request);
        } else {
            return null;
        }
    }

}
